const qc=require("./qwebchannel.js")
console.log(qc)
let socket;
const link=(callback)=>{
    console.log("link");
    let baseUrl;
    if (location.search != "")
        baseUrl = (/[?&]webChannelBaseUrl=([A-Za-z0-9\-:/\.]+)/.exec(location.search)[1]);
    else
        baseUrl = "ws://localhost:12345";

    console.log("Connecting to WebSocket server at " + baseUrl + ".");
    socket = new WebSocket(baseUrl);

    socket.onclose = function() {
        console.error("web channel closed");
    };
    socket.onerror = function(error) {
        console.error("web channel error: " + error);
    };
    socket.onopen = function() {
        console.log("WebSocket connected, setting up QWebChannel.");
        new qc.QWebChannel(socket, (channel)=> {
            // make core object accessible globally
            socket = channel.objects.core;
            socket.sendText.connect((message)=>{
                console.log("Received message: " + message);
            });
            socket.receiveText("Client connected, ready to send/receive messages!");
            console.log("Connected to WebChannel, ready to send/receive messages!");
            callback();
        });
    }
}
function init(models, callback) {
  console.log("init")
  link(callback)
}
const HOST = 'http://localhost:8000';
function get(url, data, cb, err_callback) {
  console.log(url);
  console.log(data);
  let urls = url.split('/');
  let new_url = '/get/' + urls[2];
  console.log(new_url);
  socket.emit(new_url, JSON.stringify(data),(res)=>{
    console.log(res);
    cb(JSON.parse(res))
  });
}
function delete1(url, data, cb) {
  console.log(url);
  let urls = url.split('/');
  let new_url = '/delete/' + urls[2];
  socket.emit(new_url, JSON.stringify(data),(res)=>{
    console.log(res);
    cb(JSON.parse(res))
  });
}
function post(url, data, cb) {
  console.log(url);
  console.log(data);
  let urls = url.split('/');
  let new_url = '/post/' + urls[2];
  console.log(new_url);
  socket.emit(new_url, JSON.stringify(data), (res)=>{

    cb(JSON.parse(res))
  });
}
function put(url, data, cb) {
  console.log(url);
  console.log(data);
  let urls = url.split('/');
  let new_url = '/put/' + urls[2];
  console.log(new_url);
  socket.emit(new_url, JSON.stringify(data), (res)=>{
    console.log(res);
    cb(JSON.parse(res))
  });
}
function postOrPut(url, data, cb) {
  if (data.id) {
    return put(url, data, cb);
  } else {
    return post(url, data, cb);
  }
}
function postForm(url, data, cb) {
  post(url, data, (res)=>{
    cb(res)
  });
}
function contacts(data, cb, err_callback) {
  return get('/rest/Contact', data, cb, err_callback);
}
function UsePacks(query, cb) {
  var data = { contact: query };
  return get('/rest/UsePack', data, cb);
}
function PackItems(query, cb) {
  var data = { pack: query };
  return get('/rest/PackItem', data, cb);
}
function items(query, cb) {
  var data = { search: query };
  return get('/rest/Item', data, cb);
}
function login_index(cb) {
  return get('/rest/login_index', undefined, cb, (error) => {
    alert(error + '\n请检查服务器/刷新网页/登录');
  });
}
function logout(cb) {
  return get('/rest/logout', undefined, cb);
}

function login(username, password, cb) {
  var payload = {
    username: username,
    password: password,
  };
  socket.emit('/get/login', payload, (res)=>{
    cb(res)
  });
}
var users_c=null;
function cache_users(cb){
  if(users_c===null){
    users((res)=>{
      if(res.success){
        users_c=res.data;
        cb(users_c);
      }
      else{
        console.log("not success")
      }
    });
  }
  else{
    cb(users_c);
  }
}
function users( cb) {
  var data = {};
  return get('/rest/view_user/',data,  cb);
}
function multi(data,cb,err_callback){
  post("/rest/multi/",data,cb,err_callback)
}
const Client = {
  init,
  multi,
  cache_users,
  contacts,
  items,
  login_index,
  login,
  logout,
  UsePacks,
  PackItems,
  get,
  put,
  post,
  postOrPut,
  delete1,
  postForm,
};
export default Client;
